package com.sixth.service.impl;

import com.sixth.bean.*;
import com.sixth.bean.bo.*;
import com.sixth.bean.vo.*;
import com.sixth.mapper.*;
import com.sixth.other.MarketFreight;
import com.sixth.service.AdminConfigService;
import com.sixth.service.CartService;
import com.sixth.util.ConfigUtils;
import com.sixth.util.DateUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author lixinhang
 * @Time 2022/9/11 13:02
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    AdminConfigService adminConfigService;

    //查询数据库，查询该用户的购物车中的商品个数
    @Override
    public Integer wxCartGoodscount(Integer id) {
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(id);           //user_id为当前用户id
        criteria.andDeletedEqualTo(false);//未被删除
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        int goodsCount = 0;
        for (MarketCart marketCart : marketCarts) {
            goodsCount += marketCart.getNumber();
        }
        return goodsCount;
    }

    //向id号用户的购物车中添加商品，
    @Override
    public Integer wxCartAdd(WXCartAddBO wxCartAddBO, Integer userId) {
        //先去检索数据库product表，该productId的商品库存
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(wxCartAddBO.getProductId());
        Integer storage = marketGoodsProduct.getNumber();
        if (wxCartAddBO.getNumber() > storage) {
            return null;    //如果添加数量大于商品库存，则返回null
        }

        //检索数据库goods表，根据goods_id查询goods
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(marketGoodsProduct.getGoodsId());

        //检索cart表，根据user_id、productId查询是否已存在符合条件的marketCart记录
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andDeletedEqualTo(false).andProductIdEqualTo(wxCartAddBO.getProductId()).andUserIdEqualTo(userId);
        //根据user_id,product_id,deleted查询，该list只能有一条记录或者没有记录
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        MarketCart marketCart = null;

        if (marketCarts.size() == 0) {
            //如果此前没有该型号商品的记录，向数据库中新增一条cart记录
            marketCart = new MarketCart(null, userId, marketGoodsProduct.getGoodsId(), marketGoods.getGoodsSn(), marketGoods.getName(), marketGoodsProduct.getId(),
                    marketGoodsProduct.getPrice(), wxCartAddBO.getNumber().shortValue(), marketGoodsProduct.getSpecifications(), false,
                    marketGoodsProduct.getUrl(), new Date(), new Date(), false);
            marketCartMapper.insert(marketCart);
        } else {
            //如果此前已有该型号商品的记录，修改数据库中的记录
            marketCart = new MarketCart(marketCarts.get(0).getId(), userId, null, marketGoods.getGoodsSn(), marketGoods.getName(), null,
                    marketGoodsProduct.getPrice(), (short) (wxCartAddBO.getNumber().shortValue() + marketCarts.get(0).getNumber()), marketGoodsProduct.getSpecifications(), null,
                    marketGoodsProduct.getUrl(), null, new Date(), false);
            marketCartMapper.updateByPrimaryKeySelective(marketCart);
        }

        //查询cart表中该用户的商品的数量
        MarketCartExample marketCartExample1 = new MarketCartExample();
        MarketCartExample.Criteria criteria1 = marketCartExample1.createCriteria();
        criteria1.andDeletedEqualTo(false).andUserIdEqualTo(userId);
        List<MarketCart> marketCarts1 = marketCartMapper.selectByExample(marketCartExample1);

        Integer number = 0;
        for (MarketCart cart : marketCarts1) {
            number += cart.getNumber();
        }
        return number;
    }


    //点击购物车，需要显示出该用户购物车中的商品
    //todo 商品下架后，购物车中该商品会被删除，但是商品再次上架后，购物车中该商品并不会再出现
    @Transactional
    @Override
    public WXCartIndexVO wxCartIndex(Integer userId) {
        //展示购物车之前,先去查询goods表、goods_product表，检查商品上下架是否已更改，价格是否已更改
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.setOrderByClause("update_time desc");
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        //将该用户的购物车列表，更新一下，商品下架会删除记录，但是重新上架记录不会重新出现
        criteria.andUserIdEqualTo(userId);        //指定用户id,
        criteria.andDeletedEqualTo(false); //购物车中该条记录未被删除
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        for (MarketCart marketCart : marketCarts) {
            Integer goodsId = marketCart.getGoodsId();
            Integer productId = marketCart.getProductId();
            MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(goodsId);
            //这个marketCartExample1是为了修改购物车中该行记录的状态，指定了user_id,goods_id,product_id,deleted=false,其实就锁定了一条记录
            MarketCartExample marketCartExample1 = new MarketCartExample();
            MarketCartExample.Criteria criteria1 = marketCartExample1.createCriteria();
            criteria1.andDeletedEqualTo(false).andGoodsIdEqualTo(goodsId).andUserIdEqualTo(userId).andProductIdEqualTo(productId);
            MarketCart marketCart1 = new MarketCart();
            if (marketGoods.getDeleted() || !marketGoods.getIsOnSale()) {
                //如果商品为未售或者已删除的，则要将购物车中该条记录删除
                marketCart1.setDeleted(true);
                marketCartMapper.updateByExampleSelective(marketCart1, marketCartExample1);
            } else {
                //如果该商品在售且未被删除的，则要更新数据库购物车中该商品的状态和价格
                MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);
                marketCart1.setPrice(marketGoodsProduct.getPrice());
                marketCartMapper.updateByExampleSelective(marketCart1, marketCartExample1);
            }
        }

        Integer goodsCount = 0;
        BigDecimal goodsAmount = BigDecimal.valueOf(0);
        List<WXCartIndexMarketCartVO> cartList = new ArrayList<>(); //得到cartList
        for (MarketCart marketCart : marketCarts) {
            goodsCount += marketCart.getNumber();   //查询出goodsCount
            goodsAmount = goodsAmount.add(BigDecimal.valueOf(marketCart.getNumber()).multiply(marketCart.getPrice()));
            WXCartIndexMarketCartVO wxCartIndexMarketCartVO = new WXCartIndexMarketCartVO();
            try {
                BeanUtils.copyProperties(wxCartIndexMarketCartVO, marketCart);
            } catch (Exception e) {
                e.printStackTrace();
            }
            cartList.add(wxCartIndexMarketCartVO);
        }
        goodsAmount = goodsAmount.setScale(2, BigDecimal.ROUND_DOWN);   //计算得出goodsAmount

        criteria.andCheckedEqualTo(true);
        List<MarketCart> marketCarts1 = marketCartMapper.selectByExample(marketCartExample);
        Integer checkedGoodsCount = 0;
        BigDecimal checkedGoodsAmount = BigDecimal.valueOf(0);
        for (MarketCart marketCart : marketCarts1) {
            checkedGoodsCount += marketCart.getNumber();                           //查询得出checkedGoodsCount
            checkedGoodsAmount = checkedGoodsAmount.add(BigDecimal.valueOf(marketCart.getNumber()).multiply(marketCart.getPrice()));
        }
        checkedGoodsAmount = checkedGoodsAmount.setScale(2, BigDecimal.ROUND_DOWN);//计算得出checkedGoodsAmount

        WXCartIndexCartTotalVO cartTotal = new WXCartIndexCartTotalVO(goodsCount, checkedGoodsCount, goodsAmount, checkedGoodsAmount);
        return new WXCartIndexVO(cartTotal, cartList);
    }

    //在购物车界面选中或者取消选中商品
    @Override
    public void wxCartChecked(WXCartCheckedBO wxCartCheckedBO, Integer userId) {
        Integer isChecked = wxCartCheckedBO.getIsChecked();
        Boolean checked;
        if (isChecked == 0) {
            checked = false;
        } else {
            checked = true;
        }

        List<Integer> productIds = wxCartCheckedBO.getProductIds();

        for (Integer productId : productIds) {
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andDeletedEqualTo(false).andUserIdEqualTo(userId).andProductIdEqualTo(productId);
            MarketCart marketCart = new MarketCart();
            marketCart.setChecked(checked);
            marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);
        }
    }

    //在购物车界面编辑商品
    @Override
    public Integer wxCartUpdate(WXCartUpdateBO wxCartUpdateBO) {
        //先根据productId查询一下库存
        Integer productId = wxCartUpdateBO.getProductId();
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);
        Integer stock = marketGoodsProduct.getNumber();

        Integer number = wxCartUpdateBO.getNumber();
        if (number > stock || marketGoodsProduct.getDeleted() || !marketGoodsProduct.getGoodsId().equals(wxCartUpdateBO.getGoodsId())) {
            return 404;
        }
        //更新一下cart表
        MarketCart marketCart = new MarketCart();
        marketCart.setId(wxCartUpdateBO.getId());
        marketCart.setNumber(number.shortValue());
        marketCart.setUpdateTime(new Date());
        marketCartMapper.updateByPrimaryKeySelective(marketCart);

        return 200;
    }

    //删除购物车中的商品，修改购物车中该条记录的deleted为1
    @Override
    public void wxCartDelete(List<Integer> productIds, Integer userId) {
        for (Integer productId : productIds) {
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andUserIdEqualTo(userId).andProductIdEqualTo(productId).andDeletedEqualTo(false);
            MarketCart marketCart = new MarketCart();
            marketCart.setDeleted(true);
            marketCart.setUpdateTime(new Date());
            marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);
        }
    }

    //在购物车中下单的方法 cartId=429&addressId=55&couponId=0&userCouponId=8402&grouponRulesId=0,
    //todo 好吧，去选择默认的地址和可用的最早过期的一张优惠券
    @Transactional
    @Override
    public WXCartCheckoutVO wxCartCheckout(WXOrderSubmitBo wxOrderSubmitBo, Integer userId) {
        Integer addressId = wxOrderSubmitBo.getAddressId();
        //如果addressId是当前用户的并且没有被删除的，那就按照addressId去选择地址，
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(addressId);
        WXCartCheckoutCheckedAddressVO checkedAddress = new WXCartCheckoutCheckedAddressVO();
        //如果查询到了marketAddress,marketAddress不为空，且marketAddress的用户id等于当前用户的id,该marketAddress没有被删除
        if(marketAddress != null && marketAddress.getUserId().equals(userId) && (!marketAddress.getDeleted())){
            try {
                BeanUtils.copyProperties(checkedAddress,marketAddress);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            //如果marketAddress不存在，或者其addressId不是当前用户的，就选择该用户默认地址
            MarketAddressExample marketAddressExample = new MarketAddressExample();
            MarketAddressExample.Criteria criteria = marketAddressExample.createCriteria();
            criteria.andIsDefaultEqualTo(true).andDeletedEqualTo(false).andUserIdEqualTo(userId);
            //这个marketAddressList,要么有1条记录，要么没有记录
            List<MarketAddress> marketAddressList = marketAddressMapper.selectByExample(marketAddressExample);
            //todo 如果该用户有默认地址
            if (marketAddressList.size() != 0) {
                try {
                    BeanUtils.copyProperties(checkedAddress, marketAddressList.get(0));
                    addressId = checkedAddress.getId();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
                //todo 如果该用户没有默认地址
                addressId = 0;
            }
        }

        //todo 如不指定，或者指定的优惠券该用户不可用，则显示可用优惠券的数量，否则显示指定优惠券的优惠金额
        BigDecimal goodsTotalPrice = BigDecimal.valueOf(0);

        Integer cartId = wxOrderSubmitBo.getCartId();
        ArrayList<WXCartCheckoutCheckedGoodsVO> checkedGoodsList = new ArrayList<>();
        if (cartId == 0) {
            //todo 购物车界面下单购买
            //进入购物车列表，
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria1 = marketCartExample.createCriteria();
            criteria1.andUserIdEqualTo(userId).andDeletedEqualTo(false).andCheckedEqualTo(true);
            List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
            for (MarketCart marketCart : marketCarts) {
                goodsTotalPrice = goodsTotalPrice.add(BigDecimal.valueOf(marketCart.getNumber()).multiply(marketCart.getPrice()));
                WXCartCheckoutCheckedGoodsVO wxCartCheckoutCheckedGoodsVO = new WXCartCheckoutCheckedGoodsVO();
                try {
                    BeanUtils.copyProperties(wxCartCheckoutCheckedGoodsVO,marketCart);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                checkedGoodsList.add(wxCartCheckoutCheckedGoodsVO);
            }
        } else {
            //todo 商品界面立即购买
            //根据cartId查询购物车，计算出商品金额
            MarketCart marketCart = marketCartMapper.selectByPrimaryKey(cartId);
            goodsTotalPrice = BigDecimal.valueOf(marketCart.getNumber()).multiply(marketCart.getPrice());
            WXCartCheckoutCheckedGoodsVO wxCartCheckoutCheckedGoodsVO = new WXCartCheckoutCheckedGoodsVO();
            try {
                BeanUtils.copyProperties(wxCartCheckoutCheckedGoodsVO,marketCart);
            } catch (Exception e) {
                e.printStackTrace();
            }
            checkedGoodsList.add(wxCartCheckoutCheckedGoodsVO);
        }
        goodsTotalPrice.setScale(2,BigDecimal.ROUND_DOWN);
        //根据userCouponId,userId,deleted,goodsTotalPrice查询该优惠券是否可用
        //查询该用户可用的优惠券张数
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria1 = marketCouponUserExample.createCriteria();
        Date now = new Date();
        //未被删除的、该用户名下的，可用状态的，
        criteria1.andDeletedEqualTo(false).andUserIdEqualTo(userId).andStatusEqualTo((short) 0);
        List<MarketCouponUser> marketCouponUserList = marketCouponUserMapper.selectByExample(marketCouponUserExample);
        List<MarketCoupon> marketCouponList = new ArrayList<>();
        for (MarketCouponUser marketCouponUser : marketCouponUserList) {
            //查询出couponId,
            Integer couponId1 = marketCouponUser.getCouponId();
            //判断消费券未被删除，最低消费小于消费金额，消费券可用，
            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId1);
            //该券如果是领券天数限制，则判断天数
            if (marketCoupon.getTimeType() == 0) {
                if ((!marketCoupon.getDeleted()) && marketCoupon.getMin().compareTo(goodsTotalPrice) == -1 && marketCoupon.getStatus() == 0 &&
                        DateUtils.addDay(marketCouponUser.getUpdateTime(), marketCoupon.getDays()).after(now)) {
                    marketCouponList.add(marketCoupon);
                }
            } else {
                //该券如果是起止时间限制，则判断起止时间
                if ((!marketCoupon.getDeleted()) && marketCoupon.getMin().compareTo(goodsTotalPrice) == -1 && marketCoupon.getStatus() == 0 &&
                        now.after(marketCoupon.getStartTime()) && now.before(marketCoupon.getEndTime()) ) {
                    marketCouponList.add(marketCoupon);
                }
            }
        }
        //可用优惠券的张数
        Integer availableCouponLength = marketCouponList.size();
        //获取商场运费及免运费最低消费
        List<MarketSystem> select = adminConfigService.select(MarketFreight.list);
        ConfigExpressVO configExpressVO = new ConfigExpressVO();
        ConfigUtils.getConfig(select,configExpressVO);
        BigDecimal market_express_freight_min = new BigDecimal( configExpressVO.getMarket_express_freight_min()).setScale(2, BigDecimal.ROUND_DOWN);
        BigDecimal market_express_freight_value = new BigDecimal( configExpressVO.getMarket_express_freight_value()).setScale(2,BigDecimal.ROUND_DOWN);
        BigDecimal freightPrice = market_express_freight_value;

        if(goodsTotalPrice.compareTo(market_express_freight_min) == 1){
            freightPrice = BigDecimal.valueOf(0);
        }

        BigDecimal couponPrice = new BigDecimal(0);
        Integer couponId = wxOrderSubmitBo.getCouponId();
        Integer userCouponId = wxOrderSubmitBo.getUserCouponId();
        Integer grouponRulesId = 0;
        Integer grouponPrice = 0;
        BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice);
        BigDecimal actualPrice = orderTotalPrice;

        //如果指定不选择优惠券,则不执行下面这行代码
        if (couponId != -1 && userCouponId != -1) {
            //如果选择优惠券，则去判断该张优惠券是否可用
            if (availableCouponLength > 0){
                for (MarketCouponUser marketCouponUser : marketCouponUserList) {
                    Integer tempId = marketCouponUser.getId();
                    if(tempId.equals(userCouponId)){
                        couponId = marketCouponUser.getCouponId();
                        for (MarketCoupon marketCoupon : marketCouponList) {
                            Integer tempId2 = marketCoupon.getId();
                            if(tempId2.equals(couponId)){
                                couponPrice = marketCoupon.getDiscount();
                                break;
                            }
                        }
                    }
                }
                actualPrice = orderTotalPrice.subtract(couponPrice);
                orderTotalPrice = actualPrice;
            }
        }
        WXCartCheckoutVO wxCartCheckoutVO = new WXCartCheckoutVO(grouponRulesId, actualPrice, orderTotalPrice, cartId, userCouponId, couponId, goodsTotalPrice, addressId, grouponPrice, checkedAddress, couponPrice, availableCouponLength, freightPrice, checkedGoodsList);

        return wxCartCheckoutVO;
    }

    //向购物车中快速添加商品，如果该商品已经存在，则直接更新，如果不存在，直接新增,返回值为购物车记录号
    @Override
    public Integer wxCartFastadd(WXCartAddBO wxCartAddBO, Integer userId) {
        //查询product表，得到product,校验该型号的商品库存是否足够
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(wxCartAddBO.getProductId());
        Integer number = wxCartAddBO.getNumber();
        if (marketGoodsProduct.getNumber() < number) {
            return null;
        }
        //查询商品表，查询marketGoods
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(wxCartAddBO.getGoodsId());

        //查询购物车表，判断该用户、该型号商品、未被删除的记录是否已存在
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andDeletedEqualTo(false).andProductIdEqualTo(wxCartAddBO.getProductId()).andUserIdEqualTo(userId);
        //marketCarts的长度要么是0，要么是1
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);

        if (marketCarts.size() == 0) {
            //如果该用户购物车中没有未被删除的该型号商品，则直接新增
            MarketCart marketCart = new MarketCart(null, userId, wxCartAddBO.getGoodsId(), marketGoods.getGoodsSn(), marketGoods.getName(), marketGoodsProduct.getId(), marketGoodsProduct.getPrice(),
                    number.shortValue(), marketGoodsProduct.getSpecifications(), true, marketGoodsProduct.getUrl(), new Date(), new Date(), false);
            marketCartMapper.insertSelective(marketCart);
            return marketCart.getId();
        }
        //如果该用户购物车中已经有了未被删除的该型号商品，则更新
        MarketCart marketCart = marketCarts.get(0);
        marketCart.setGoodsSn(marketGoods.getGoodsSn());
        marketCart.setGoodsName(marketGoods.getName());
        marketCart.setPrice(marketGoodsProduct.getPrice());
        marketCart.setNumber(number.shortValue());
        marketCart.setSpecifications(marketGoodsProduct.getSpecifications());
        marketCart.setChecked(true);
        marketCart.setPicUrl(marketGoodsProduct.getUrl());
        marketCart.setAddTime(new Date());
        marketCart.setUpdateTime(new Date());
        marketCartMapper.updateByPrimaryKeySelective(marketCart);
        return marketCart.getId();
    }


}
